package main

import (
	"context"
	"fmt"
	"io/ioutil"
	"net/http"
	"os"
	"syscall"
	"time"

	"gitee.com/zhangxinzx/egapp/pkg/app"
	"gitee.com/zhangxinzx/egapp/pkg/router"
	"gitee.com/zhangxinzx/egapp/pkg/server"
	"github.com/sirupsen/logrus"
	"golang.org/x/sync/errgroup"
)

func init() {
	logrus.SetFormatter(&logrus.TextFormatter{TimestampFormat: "2006-01-02 15:04:05", FullTimestamp: true})
}

func main() {
	pprofSrv := server.NewHttp(server.Address(":8080"), server.HttpHandler(router.NewPprofRouter()), server.HttpServerName("pprof"))
	echoSrv := server.NewHttp(server.Address(":8081"), server.HttpHandler(router.NewEchoRouter()), server.HttpServerName("echo"))

	eg, ectx := errgroup.WithContext(context.Background())
	eg.Go(func() error {
		app := app.New(app.Server(pprofSrv, echoSrv), app.Context(ectx))
		return app.Run()
	})
	eg.Go(func() error {
		time.Sleep(2 * time.Second) //waiting server app to be ready
		logrus.Info("main: sending ping request to http://localhost:8081/echo/ping ...")
		resp, err := http.Get("http://localhost:8081/echo/ping")
		if err != nil {
			return fmt.Errorf("request for /echo/ping failed with %w", err)
		}
		defer resp.Body.Close()
		respBts, err := ioutil.ReadAll(resp.Body)
		if err != nil {
			return fmt.Errorf("request for /echo/ping failed with %w", err)
		}
		logrus.Infof("main: received ping response %s", string(respBts))

		logrus.Info("main: sending echo request to http://localhost:8081/echo/zhangxin ...")
		resp, err = http.Get("http://localhost:8081/echo/zhangxin")
		if err != nil {
			return fmt.Errorf("request for /echo/zhangxin failed with %w", err)
		}
		defer resp.Body.Close()
		respBts, err = ioutil.ReadAll(resp.Body)
		if err != nil {
			return fmt.Errorf("request for /echo/zhangxin failed with %w", err)
		}
		logrus.Infof("main: received echo response %s", string(respBts))

		time.Sleep(5 * time.Second)
		process, err := os.FindProcess(os.Getpid())
		if err != nil {
			return fmt.Errorf("cannot find current process through system call %w", err)
		}
		logrus.Infof("main: sending SIGINT to current process [pid %d] ...", os.Getpid())
		process.Signal(syscall.SIGINT)

		return nil
	})

	if err := eg.Wait(); err != nil {
		logrus.Errorf("main: eg group run failed with %s", err.Error())
	}
}
